<?php
/**
 * Created by 胡祥能 on 2018/4/25.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Controllers\Admin;


use App\Helpers\Api\ApiResponse;
use App\Models\Project;
use App\Models\ProjectAccept;
use App\Models\ProjectCheck;
use App\Models\ProjectExecute;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Exception;
use Log;

class ProjectController extends DefaultController
{

    use ApiResponse;

    public function apply(Request $request)
    {
        if ($request->method() == 'POST') {
            $validator = Validator::make($request->all(), [
                'name' => 'bail|required|max:100',
                'money' => 'bail|required|max:5',
                'reason' => 'bail|required|max:200',
                'frist_party' => 'bail|required|max:100',
            ]);

            $user = session(User::SESSION_KEY);

            $project = new Project();
            $project->name = $request->name;
            $project->reason = $request->reason;
            $project->money = $request->money;
            $project->first_party = $request->first_party;
            $project->uid = $user['id'];
            $res = $project->save();

            if ($res) {
                return $this->successView('', '/project/apply_list');
            } else {
                return $this->failView('', '/project/apply_list');
            }

        } else {
            return view('admin.project.apply');
        }
    }

    public function applyList(Request $request)
    {
        $perPage = $request->input('perPage', 10);

        $name = $request->input('name', '');
        $status = (int)$request->input('status', -1);

        $sql = DB::table('projects')
            ->select('projects.*', 'users.name as user_name')
            ->leftJoin('users', 'users.id','=', 'projects.uid');

        if($name){
            $sql = $sql->where('projects.name', $name)->orWhere('users.name', $name);
        }
        if($status >= 0){
            $sql = $sql->where('projects.status', $status);
        }
        $list = $sql->paginate($perPage);
        return view('admin.project.apply-list', ['list' => $list, 'query'=>$request->all()]);
    }

    public function checkList(Request $request)
    {
        $perPage = $request->input('perPage', 10);
        $name = $request->input('name', '');
        $status = (int)$request->input('status', -1);

        $sql = DB::table('projects')
            ->select('projects.*', 'users.name as user_name','check.uid as check_uid')
            ->leftJoin('users', 'users.id','=', 'projects.uid')
            ->leftJoin('project_check as check','check.pid','=','projects.id');

        if($name){
            $sql = $sql->where('projects.name', $name)->orWhere('users.name', $name);
        }

        if($status >= 0){
            $sql = $sql->where('projects.status', $status);
        }
        $list = $sql->paginate($perPage);
        return view('admin.project.check-list', ['list' => $list, 'query'=>$request->all()]);
    }

    public function check(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pid' => 'bail|required',
            'status' => 'bail|required',
            'reamark' => 'bail|required|max:255',
        ]);

        $project = Project::find($request->pid);
        if(!$project){
            return $this->json(2002);
        }elseif($project->status != 0){
            return $this->json(2003);
        }

        try {
            DB::beginTransaction();
            $user = session(User::SESSION_KEY);

            $projectCheck = new ProjectCheck();
            $projectCheck->status = $request->status;
            $projectCheck->remark = $request->remark;
            $projectCheck->pid = $request->pid;
            $projectCheck->uid = $user['id'];
            $res = $projectCheck->save();

            $res2 = Project::where('id', $request->pid)->update(['status'=>$request->status]);
            if ($res && $res2) {
                DB::commit();
                return $this->json(200);
            } else {
                DB::rollBack();//出异常，回滚
                return $this->json(1003);
            }
        } catch (Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->json(1003);
        }
    }

    public function executeList(Request $request)
    {
        $perPage = $request->input('perPage', 10);
        $name = $request->input('name', '');
        $status = (int)$request->input('status', -1);

        $where = [
            ['projects.status', 1]//只显示审核成功的
        ];
        $sql = DB::table('projects')
            ->select('projects.*', 'users.name as user_name')
            ->leftJoin('users', 'users.id','=', 'projects.uid')
            ->where($where);

        if($name){
            $sql = $sql->where('projects.name', $name);
        }

        if($status >= 0){
            $sql = $sql->where('projects.execute_status', $status);
        }

        $list = $sql->paginate($perPage);
        return view('admin.project.execute-list', ['list' => $list, 'query'=>$request->all()]);
    }

    public function executeStart(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pid' => 'bail|required',
            'deadline' => 'bail|required',
        ]);

        $project = Project::find($request->pid);
        if(!$project){
            return $this->json(2002);
        }elseif($project->status != 1){
            return $this->json(2004);
        }elseif($project->execute_status != 0){
            return $this->json(2005);
        }

        try {
            DB::beginTransaction();
            $user = session(User::SESSION_KEY);

            $projectExecute = new ProjectExecute();
            $projectExecute->deadline = $request->deadline.' 23:59:59';
            $projectExecute->remark = $request->remark;
            $projectExecute->pid = $request->pid;
            $projectExecute->uid = $user['id'];
            $res = $projectExecute->save();

            $res2 = Project::where('id', $request->pid)->update(['execute_status'=> 1]);
            if ($res && $res2) {
                DB::commit();
                return $this->json(200);
            } else {
                DB::rollBack();//出异常，回滚
                return $this->json(1003);
            }
        } catch (Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->json(1003);
        }
    }

    public function complete(Request $request)
    {
        $pid = $request->pid;
        if (!$pid) {
            return $this->json(1001);
        }

        $project = Project::find($request->pid);
        if(!$project){
            return $this->json(2002);
        }elseif($project->status != 1){
            return $this->json(2004);
        }elseif($project->execute_status != 1){
            return $this->json(2006);
        }

        try {
            DB::beginTransaction();
            $res = Project::where('id', $pid)->update([
                'execute_status'=>2//已完成
            ]);
            $res2 = ProjectExecute::where('pid', $pid)->update([
                'complete_time'=> date('Y-m-d H:i:s'),
                'status'=>2
            ]);
            if ($res && $res2) {
                DB::commit();
                return $this->json(200);
            } else {
                DB::rollBack();//出异常，回滚
                return $this->json(1003);
            }
        } catch (Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->json(1003);
        }

    }

    public function acceptList(Request $request)
    {
        $perPage = $request->input('perPage', 10);
        $name = $request->input('name', '');
        $where = [
            ['projects.status', 1],//审核成功的
            ['projects.execute_status', 2]//已完成的
        ];
        if($name){
            array_push($where, ['projects.name', $name]);
        }
        $list = DB::table('projects')
            ->select('projects.*', 'users.name as user_name','check.created_at as check_time','execute.created_at as execute_time')
            ->leftJoin('users', 'users.id','=', 'projects.uid')
            ->leftJoin('project_check as check','check.pid','=','projects.id')
            ->leftJoin('project_execute as execute', 'execute.pid','=','projects.id')
            ->where($where)
            ->paginate($perPage);
        return view('admin.project.accept-list', ['list' => $list, 'query'=>$request->all()]);
    }

    public function accept(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pid' => 'bail|required',
            'status' => 'bail|required',
            'reamark' => 'bail|required|max:255',
        ]);

        $project = Project::find($request->pid);
        if(!$project){
            return $this->json(2002);
        }elseif($project->status != 0){
            return $this->json(2003);
        }elseif($project->execute_status != 2){
            return $this->json(2007);
        }elseif($project->accept_status != 0){
            return $this->json(2008);
        }

        try {
            DB::beginTransaction();
            $user = session(User::SESSION_KEY);

            $projectAccept = new ProjectAccept();
            $projectAccept->status = $request->status;
            $projectAccept->remark = $request->remark;
            $projectAccept->pid = $request->pid;
            $projectAccept->uid = $user['id'];
            $res = $projectAccept->save();

            $res2 = Project::where('id', $request->pid)->update(['accept_status'=>$request->status]);
            if ($res && $res2) {
                DB::commit();
                return $this->json(200);
            } else {
                DB::rollBack();//出异常，回滚
                return $this->json(1003);
            }
        } catch (Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->json(1003);
        }
    }

    public function generalList(Request $request)
    {
        $perPage = $request->input('perPage', 10);
        $name = $request->input('name', '');
        $where = [
            ['projects.status', 1],//审核成功的
            ['projects.execute_status', 2]//已完成的
        ];
        if($name){
            array_push($where, ['projects.name', $name]);
        }
        $list = DB::table('projects')
            ->select('projects.*', 'users.name as user_name','check.created_at as check_time','execute.created_at as execute_time','accept.created_at as accept_time')
            ->leftJoin('users', 'users.id','=', 'projects.uid')
            ->leftJoin('project_check as check','check.pid','=','projects.id')
            ->leftJoin('project_execute as execute', 'execute.pid','=','projects.id')
            ->leftJoin('project_accept as accept', 'accept.pid','=','projects.id')
            ->where($where)
            ->paginate($perPage);
        if($request->type == 'ajax'){
            return $this->json(200, $list);
        }else{
            return view('admin.project.general-list');
        }
    }
}